<template>
  <div>
    <el-dialog v-model="dialogFormVisible" :title="props.type == 'add' ? '添加职位' : '修改职位'">
      <el-form ref="formRef" :model="form">
        <el-form-item label="职位名称" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save($parent)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reqAddRole, reqUpdateRole } from '@/utils/api/acl/role'
import { RoleData } from '@/utils/api/acl/role/type'
import { reactive, ref } from 'vue'

const props = defineProps({
  type: String
})

const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
// 表单的ref
const formRef = ref()

const form = reactive({
  roleName: ''
})

// 改变对话框的显示并获取row
const changeShow = (row: RoleData) => {
  Object.assign(form, row)
  dialogFormVisible.value = true
}

// 保存按钮
const save = async ($parent: any) => {
  if (props.type == 'add') {
    const res = await reqAddRole(form)
    if (res.data.code == 200) {
      ElMessage.success('保存成功')
      $parent.$parent.getRoleTable($parent.$parent.currentPage)
      dialogFormVisible.value = false
      clearForm()
    }
  } else {
    const res = await reqUpdateRole(form)
    if (res.data.code == 200) {
      ElMessage.success('修改成功')
      $parent.$parent.getRoleTable($parent.$parent.currentPage)
      dialogFormVisible.value = false
      clearForm()
    }
  }
}

// 取消按钮
const cancel = () => {
  dialogFormVisible.value = false
  clearForm()
}

// 清除表单
const clearForm = () => {
  formRef.value.resetFields()
}

defineExpose({ changeShow })
</script>

<style scoped></style>
